package com.matt.docpro.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.matt.docpro.config.Utils;
import com.matt.docpro.model.*;
import com.matt.docpro.service.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Stream;

/**
 * DoctorController
 * Created by  on 2024/02/07.
 */
@Controller
public class DoctorController {

    @Autowired
    AppointmentService appointmentService;
    @Autowired
    ReviewService reviewService;
    @Autowired
    DoctorService doctorService;
    @Autowired
    PatientService patientService;
    @Autowired
    LoginInfoService loginInfoService;
    @Autowired
    OutcomeService outcomeService;
    @Autowired
    ClinicService clinicService;

    @RequestMapping("/doctors-dashboard")
    public String init(Model model, HttpServletRequest request) throws Exception {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        if (!user.getRole().equals("1")) {
            return "redirect:/error403";
        }
        List<Appointment> appointments = appointmentService.getByDocId(user.getId());
        model.addAttribute("appointments", appointments);
        int patientCount = appointmentService.getPatCountByDocId(user.getId());
        int doctorCount = doctorService.getCount();
        int appointmentCount = appointmentService.getCountByDocId(user.getId());
        Doctor doctor = doctorService.getById(user.getId());
        model.addAttribute("patientCount", patientCount);
        model.addAttribute("doctorCount", doctorCount);
        model.addAttribute("appointmentCount", appointmentCount);
        model.addAttribute("doctor", doctor);
        model.addAttribute("user", user);
        return "doctors-dashboard";
    }

    @RequestMapping("/my-patients")
    public String patients(Model model, HttpServletRequest request) {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        Doctor doctor = doctorService.getById(user.getId());
        List<Patient> patients = appointmentService.getPatByDocId(user.getId());
        model.addAttribute("patients", patients);
        model.addAttribute("doctor", doctor);
        model.addAttribute("user", user);
        return "my-patients";
    }

    @RequestMapping("/change-password")
    public String changePassword(Model model, HttpServletRequest request) {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        Doctor doctor = doctorService.getById(user.getId());
        model.addAttribute("doctor", doctor);
        model.addAttribute("user", user);
        return "change-password";
    }

    @PostMapping("/doctors-dashboard/setState")
    @ResponseBody
    public Map<String, Object> setState(String id, String stateId) {
        Map<String, Object> res = new HashMap<>();
        Appointment appointment = appointmentService.setState(id, stateId);
        res.put("state", "success");
        res.put("appointmentState", appointment.getStateId());
        return res;
    }

    @RequestMapping("/review")
    public String review(Model model, HttpServletRequest request) throws Exception {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        Doctor doctor = doctorService.getById(user.getId());
        List<Review> reviews = reviewService.getByDocId(user.getId());
        model.addAttribute("doctor", doctor);
        model.addAttribute("reviews", reviews);
        model.addAttribute("user", user);
        return "review";
    }

    @RequestMapping("/doc-outcome")
    public String docOutcome(Model model, HttpServletRequest request) {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        Doctor doctor = doctorService.getById(user.getId());
        // 日期数据，最近5天
        Map<Integer, List<String>> dateMap = new LinkedHashMap<>();
        DateTime today = DateUtil.date();
        String todayStr = DateUtil.format(today, "yyyy/MM/dd");
        String todayShowStr = DateUtil.format(today, "MM-dd")+" "+Utils.getWeekDay(today);
        List<String> dateStrList = new ArrayList<>();
        dateStrList.add(todayStr);
        dateStrList.add(todayShowStr);
        dateMap.put(1, dateStrList);
        String endDtStr = null;
        for (int i = 1; i < 5; i++) {
            DateTime nextDay = DateUtil.offsetDay(today, i);
            String nextDayStr = DateUtil.format(nextDay, "yyyy/MM/dd");
            String nextDayShowStr = DateUtil.format(nextDay, "MM-dd")+" "+Utils.getWeekDay(nextDay);
            List<String> nextDateStrList = new ArrayList<>();
            nextDateStrList.add(nextDayStr);
            nextDateStrList.add(nextDayShowStr);
            dateMap.put(i+1, nextDateStrList);
            endDtStr = nextDayStr;
        }
        model.addAttribute("dateMap", dateMap);

        List<Outcome> outcomeList0 = new ArrayList<>();
        List<Outcome> outcomeList1 = new ArrayList<>();
        List<Outcome> outcomeList2 = new ArrayList<>();
        List<Outcome> outcomeList3 = new ArrayList<>();
        List<Outcome> outcomeList0tmp = outcomeService.getOutcomeByDateRangeClinicDocStage(todayStr, endDtStr, doctor.getClinicId(), doctor.getId(), 0);
        List<Outcome> outcomeList1tmp = outcomeService.getOutcomeByDateRangeClinicDocStage(todayStr, endDtStr, doctor.getClinicId(), doctor.getId(), 1);
        List<Outcome> outcomeList2tmp = outcomeService.getOutcomeByDateRangeClinicDocStage(todayStr, endDtStr, doctor.getClinicId(), doctor.getId(), 2);
        List<Outcome> outcomeList3tmp = outcomeService.getOutcomeByDateRangeClinicDocStage(todayStr, endDtStr, doctor.getClinicId(), doctor.getId(), 3);
        for (int i = 1; i <= 5; i++) {
            String date = dateMap.get(i).get(0);
            outcomeList0.add(outcomeList0tmp.stream().filter(p -> p.getDate().equals(date)).findFirst().orElse(null));
            outcomeList1.add(outcomeList1tmp.stream().filter(p -> p.getDate().equals(date)).findFirst().orElse(null));
            outcomeList2.add(outcomeList2tmp.stream().filter(p -> p.getDate().equals(date)).findFirst().orElse(null));
            outcomeList3.add(outcomeList3tmp.stream().filter(p -> p.getDate().equals(date)).findFirst().orElse(null));
        }

        model.addAttribute("outcomeList0", outcomeList0);
        model.addAttribute("outcomeList1", outcomeList1);
        model.addAttribute("outcomeList2", outcomeList2);
        model.addAttribute("outcomeList3", outcomeList3);
        model.addAttribute("doctor", doctor);
        model.addAttribute("user", user);
        return "doc-outcome";
    }

    @PostMapping("/doc-outcome/save")
    @ResponseBody
    public Map<String, Object> docOutcomeSave(Model model, Outcome outcome) {
        Map<String, Object> res = new HashMap<>();
        Doctor doctor = doctorService.getById(outcome.getDocId());
        outcome.setClinicId(doctor.getClinicId());
        Outcome outcomeTmp = outcomeService.get(outcome);
        if (outcomeTmp != null) {
            outcomeService.updateState(outcome);
        } else {
            outcomeService.insert(outcome);
        }
        res.put("state", "success");
        return res;
    }

    @RequestMapping("/my-profile")
    public String myProfile(Model model, HttpServletRequest request) throws Exception {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        Doctor doctor = doctorService.getById(user.getId());
        List<Clinic> clinics = clinicService.getAll();
        model.addAttribute("doctor", doctor);
        model.addAttribute("clinics", clinics);
        model.addAttribute("user", user);
        return "my-profile";
    }

    @PostMapping("/my-profile/save")
    @ResponseBody
    public Map<String, Object> myProfile(Model model, Doctor doctor, MultipartFile iconFile) {
        Map<String, Object> res = new HashMap<>();
        String filePath = Utils.uploadFile(iconFile, doctor.getId());
        if (filePath != null) {
            doctor.setIcon(filePath);
        }
        doctorService.update(doctor);
        res.put("state", "success");
        return res;
    }

    @RequestMapping("/doctors-2")
    public String doctorList(Model model, HttpServletRequest request) throws Exception {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        List<Doctor> doctors = doctorService.getAll();
        for (Doctor doctor : doctors) {
            doctor.setReviewCount(reviewService.getCountByDocId(doctor.getId()));
            doctor.setAvgLevel(reviewService.getAvgLevelByDocId(doctor.getId()));
        }
        model.addAttribute("doctors", doctors);
        model.addAttribute("user", user);
        return "doctors-2";
    }

    @RequestMapping("/doctors-details")
    public String doctorsDetail(Model model, String docId, HttpServletRequest request) throws Exception {
        String token = Utils.getToken(request);
        User user = loginInfoService.getUserByToken(token);
        Doctor doctor = doctorService.getById(docId);
        doctor.setReviewCount(reviewService.getCountByDocId(docId));
        doctor.setAvgLevel(reviewService.getAvgLevelByDocId(docId));
        model.addAttribute("doctor", doctor);
        model.addAttribute("user", user);
        return "doctors-details";
    }

}
